package cn.edu.zafu.bigdata.lyq.work7;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileWrite {
    // 将文本写入文件的方法
    public static void writeToFile(String fileName, String content) {
        try {
            FileWriter writer = new FileWriter(fileName);
            writer.write(content);
            writer.close();
            System.out.println("文本已成功写入文件。");
        } catch (IOException e) {
            System.out.println("写入文件时出错：" + e.getMessage());
        }
    }

    // 从文件中读取内容并打印到控制台的方法
    public static void readFromFile(String fileName) {
        try {
            File file = new File(fileName);
            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("读取文件时出错：找不到文件 " + fileName + "，错误信息：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入要保存的文本内容：");
        String inputText = scanner.nextLine();
        String fileName = "202203090213.txt";

        writeToFile(fileName, inputText);

        readFromFile(fileName);

        scanner.close();
    }
}




